#include <p18f4550.h>
#include <delays.h>

#pragma config FOSC = INTOSCIO_EC //Internal oscillator, port function on RA6, EC used by USB 
#pragma config WDT = OFF //Disable watchdog timer

void interrupt_handler();
 
volatile int counter=0;
int i=0;
void task1(){LATDbits.LATD4=1;LATDbits.LATD0^=1;LATDbits.LATD4=0;}
void task2(){LATDbits.LATD5=1;LATDbits.LATD1^=1;LATDbits.LATD5=0;}
void task3(){LATDbits.LATD6=1;LATDbits.LATD2^=1; for(i=0;i<1000;i++);LATDbits.LATD6=0;}
void task4(){LATDbits.LATD7=1;LATDbits.LATD3^=1;LATDbits.LATD7=0;}
void(*currentTask)(void);



#pragma code isr=0x08
void high_vector()
{
_asm GOTO interrupt_handler _endasm
}
#pragma code

#pragma interrupt interrupt_handler
void handle_tasks();
void interrupt_handler()
{
        TMR0H=0xFC;
        TMR0L=0x17;
        counter++;
        handle_tasks();
        INTCONbits.TMR0IF=0; //reset interrupt
        
}

void handle_tasks()
{
        if (counter%50==0)
                {currentTask=&task1;
				currentTask();
                        
                        if (counter%100==0)
                        {
                                currentTask=&task2;
								currentTask();
                                        
                        
                                if (counter%200==0)
                                {
                                        currentTask=&task3;
										currentTask();
                                        
									if (counter%400==0)
                                        {
                                        currentTask=&task4;
										currentTask();
                                        
                                        }
                                }
                                
                        }       
                        
                        //counter++;
                }
        if(counter>=40000)
        {counter=0;}
}

void initialize()
{
        OSCCONbits.IRCF2=1; //110 = 4 MHz
		OSCCONbits.IRCF1=1;
		OSCCONbits.IRCF0=0;
        OSCCONbits.SCS=2;       //1x = Internal oscillator

        T0CONbits.T08BIT=0;//0 = Timer0 is configured as a 16-bit timer/counter
        T0CONbits.T0CS=0; //0 = Internal instruction cycle clock (CLKO)
        T0CONbits.PSA=1; //1 = TImer0 prescaler is NOT assigned. Timer0 clock input bypasses prescaler.
       // T0CONbits.T0PS=1; //011 = 1:4 Prescale value

        INTCONbits.TMR0IE=1;//1 = Enables the TMR0 overflow interrupt
        
        
        TRISD=0;
        LATD=9;
        

        
        INTCONbits.GIE=1; //enable interrupts
        TMR0H=0xFC;
        TMR0L=0x17;
        T0CONbits.TMR0ON=1; //starts timer0
}

void main()
{
        initialize();LATD=0x00;
        while(1)
        {   
        
        }
}
